import { getCookie, setCookie } from './utils/stoage'
import router, { back, jump } from './router'
import Toast from './components/widgets/toast'

export const baseURL = process.env.NODE_ENV === 'production' ?
  'https://r209.chaoshenwan.com/lottery' :
  'https://r209.chaoshenwan.com/lottery'  // 所有请求的根路径

const body = Object.assign({
  timestamp: Date.now(),
  channelId: 'A100001',
  platform: 2,
  version: '1.0.0'
}, getCookie('signature', true))

const http = {}

http.signature = function (signature) {
  var assign = Object.assign(body, signature)
  setCookie('signature', JSON.stringify(assign))
}

http.get = function (url, params) {
  return ajax(url, 'GET', params)
}

http.post = function (url, params) {
  return ajax(url, 'POST', params)
}

http.delete = function (url, params) {
  return ajax(url, 'DELETE', params)
}

export const ajax = function (url, method, params) {
  var options = {
    credentials: 'include', // pass cookies, for authentication
    method
  }

  options.heasers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }

  body.data = JSON.stringify(params)

  // options.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  options.body = JSON.stringify(body)

  /* ajax with fetch API */
  return new Promise((resolve, reject) => {
    fetch(baseURL + url, options).then(function (response) {
      if (response.ok) {
        response.json().then(function (json) {
          if (json.head.code === 1) {
            resolve(json.data)
          } else {
            Toast(json.head.msg)
            reject(json.head)
            if (json.head.code == 21) {
              var route = router.currentRoute
              var path = '/login?from=' + route.path
              var query = querystring(route.query)
              if (query) {
                path += '%3F' + query
              }
              jump(path)
            }
          }
        })
      } else {
        throw new Error('Network response was not ok.')
      }
    }).catch(function (error) {
      Toast.fail(error)
      reject(error)
      back()
    })
  })
}

function querystring (obj) {
  return Object.keys(obj).map(function (key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
  }).join('&')
}

export function checkout (url, type, data, cleanFunc, index) {
  var vm = this
  http.post(url, data).then(o => {
    if (this.app) {
      location = `checkout://orderId=${o.id}&amount=${o.amount}&lotteryType=${o.lotteryType}`
      cleanFunc()
      return
    }
    http.post('/order/payOrder', {orderId: o.id}).then(() => {
      vm.$store.dispatch('fetch')
      vm.$dialog.confirm({
        title: '支付成功',
        message: '该订单已支付成功，购物车已被清空',
        confirmButtonText: '转到选择页',
        cancelButtonText: '查看订单'
      }).then(() => {
        cleanFunc()
        vm.$router.replace(index || ('/' + type))
      }).catch(() => {
        cleanFunc()
        vm.$router.replace(`/${type}/order?id=${o.id}`)
      })
    })
  })
}

export default http
